const router = require('koa-router')()
const {
	sqlquery
} = require('../APP/LK.js')
const md5 = require('md5')

router.prefix('/admin')


const multer = require('koa-multer');
//配置    
var storage = multer.diskStorage({
	//文件保存路径
	destination: function(req, file, cb) {
		cb(null, 'public/uploads') //注意路径必须存在
	},
	//修改文件名称
	filename: function (req, file, cb) {
		var fileFormat = (file.originalname).split(".");
		cb(null, Date.now() + "." + fileFormat[fileFormat.length - 1]);
	}
})


//加载配置
var upload = multer({
	storage: storage
})

router.get('*', async function (ctx, next) {
	let token = ctx.query.token
	console.log(token)
	console.log(ctx.url)
	console.log(ctx.session.token)
	if (ctx.url != '/admin/login') {
		if (!token) {
			ctx.body = {
				code: 400,
				msg: '参数错误'
			}
			return false
		}
		if (token != ctx.session.token) {
			ctx.body = {
				code: 400,
				msg: '参数错误'
			}
		} else {
			console.log('aaaa')
			await next()
		}
	} else {
		await next()
	}
})

//后台登录
router.post('/login', async function (ctx, next) {
	let username = ctx.request.body.username
	let password = ctx.request.body.password

	let sql = "select * from admin where username='" + username + "'";
	let res = await sqlquery(sql)

	if (res.length > 0) {
		password = md5(password)
		console.log(password)
		if (password != res[0].password) {
			ctx.body = {
				code: '400',
				msg: '密码错误'
			}
		} else {
			let token = md5(username + '123')
			ctx.session.token = token
			ctx.body = {
				code: '200',
				msg: '登录成功',
				username,
				token
			}
		}
	} else {
		ctx.body = {
			code: '400',
			msg: '账号不存在'
		}
	}
})

//获取经纪人列表+搜索
router.get('/getbrokerlist', async function (ctx, next) {
	let name = ctx.query.ss
	let set = parseInt(ctx.query.set)


	let sql = `SELECT
	b.*, c.company_name,
	count(CASE WHEN h.state = 1 THEN h.state ELSE null END) AS state1,
		count(CASE WHEN h.state = 2 THEN h.state ELSE null END) AS state2,
		count(CASE WHEN h.state = 3 THEN h.state ELSE null END) AS state3
	FROM
	broker b
	LEFT JOIN houses h ON b.id = h.broker_id
	LEFT JOIN company c ON c.id = b.company
	where 1=1 `
	if (set) {
		sql += " and b.state=" + set;
	}
	if (name) {
		sql += " and (b.name= '" + name + "' or b.phone='" + name + "') ";
	}
	sql += ` GROUP BY
	b.id `;

	// console.log(sql)


	let res = await sqlquery(sql);

	ctx.body = {
		code: '200',
		msg: '查询成功',
		res
	}

})


//经纪人删除
router.get('/delbroker', async function (ctx, next) {
	let id = ctx.query.id

	let sql = "delete from broker where id=" + id;

	let res = await sqlquery(sql);


	ctx.body = {
		code: '200',
		msg: '删除成功'
	}
})

//公司查询
router.get('/getcompany', async function (ctx, next) {

	let sql = "select * from company";

	let res = await sqlquery(sql);


	ctx.body = {
		code: '200',
		msg: '查询成功',
		res
	}
})

//新建经纪人
router.post('/addbroker', async function (ctx, next) {
	let name = ctx.request.body.name
	let phone = ctx.request.body.phone
	let password = md5(ctx.request.body.password)
	let company = ctx.request.body.company


	let sql = "insert into broker (name,phone,company,password,state) values('" + name + "','" + phone +
		"'," + company + ",'" + password + "',1)";

	await sqlquery(sql);


	ctx.body = {
		code: '200',
		msg: '新建成功'
	}
})


//经纪人状态修改
router.post('/setbrokerstate', async function (ctx, next) {
	let id = ctx.request.body.id
	let state = ctx.request.body.state

	let sql = "update broker set state=" + state + " where id=" + id;

	let res = await sqlquery(sql);


	ctx.body = {
		code: '200',
		msg: '修改成功',
	}
})

//经纪人数据修改
router.post('/setbroker', async function (ctx, next) {
	let id = ctx.request.body.id
	let name = ctx.request.body.name
	let phone = ctx.request.body.phone
	let password = md5(ctx.request.body.password)
	let company = ctx.request.body.company

	let sql = "update broker set name='" + name + "',phone='" + phone + "',password='" + password +
		"',company=" + company + " where id=" + id;

	await sqlquery(sql);


	ctx.body = {
		code: '200',
		msg: '修改成功'
	}
})

//咨询数据查询
router.get('/getinformation', async function (ctx, next) {

	let title = ctx.query.title

	let sql = "select * from information";

	if (title) {
		sql += " where information_title like '%" + title + "%'"
	}

	let res = await sqlquery(sql);


	ctx.body = {
		code: '200',
		msg: '查询成功',
		res
	}
})

//咨询数据删除
router.get('/delinformation', async function (ctx, next) {
	let id = ctx.query.id

	let sql = "delete from information where id=" + id;

	let res = await sqlquery(sql);


	ctx.body = {
		code: '200',
		msg: '删除成功'
	}
})


//获取当前时间
Date.prototype.Format = function (fmt) {
	var o = {
		"M+": this.getMonth() + 1, //月份 
		"d+": this.getDate(), //日 
		"H+": this.getHours(), //小时 
		"m+": this.getMinutes(), //分 
		"s+": this.getSeconds(), //秒 
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度 
		"S": this.getMilliseconds() //毫秒 
	};
	if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : ((
			"00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}

//新建资讯数据+图片
router.post('/addinformation', upload.single('file'), async (ctx, next) => {
	let file = ctx.req.file.filename
	file = '/uploads/' + file
	let title = ctx.req.body.title
	let textarea = ctx.req.body.textarea
	let time = new Date().Format("yyyy-MM-dd HH:mm:ss")
	let number = 0;
	let state = 1

	let sql = "insert into information values(null,'" + file + "','" + title + "','" + time + "'," +
		number +
		"," + state +
		",'" + textarea + "')";

	console.log(sql)
	await sqlquery(sql)
	ctx.body = {
		code: '200',
		msg: '新建成功'
	}
});

//修改资讯数据
router.post('/setinformation', async function (ctx, next) {
	let id = ctx.request.body.id
	let title = ctx.request.body.title
	let textarea = ctx.request.body.textarea
	let time = new Date().Format("yyyy-MM-dd HH:mm:ss")

	let sql = "update information set information_title='" + title + "',information_desc='" + textarea +
		"',information_time='" + time +
		"' where id=" + id;

	await sqlquery(sql);


	ctx.body = {
		code: '200',
		msg: '修改成功'
	}
})

//房源数据查询
router.get('/gethouses', async function(ctx, next) {

	let title = ctx.query.title

	let sql =
		"select houses.*,plot.plot_site from houses join plot on houses.plot_id = plot.id where houses.house_state=1";

	if (title) {
		sql += " and houses.title like '%" + title + "%'"
	}

	let res = await sqlquery(sql);


	ctx.body = {
		code: '200',
		msg: '查询成功',
		res
	}
})

//房源数据删除
router.get('/delhouses', async function(ctx, next) {
	let id = ctx.query.id

	let sql = "delete from houses where id=" + id;

	let res = await sqlquery(sql);


	ctx.body = {
		code: '200',
		msg: '删除成功'
	}
})


//查找小区表
router.get('/getplot', async function(ctx, next) {

	let sql = "select * from plot"

	let res = await sqlquery(sql);

	ctx.body = {
		code: '200',
		msg: '查询成功',
		res
	}
})

//新建房源
router.post('/addhouses', async function(ctx, next) {
	let state = ctx.request.body.state
	let title = ctx.request.body.title
	let describes = ctx.request.body.describes
	let phone = ctx.request.body.phone
	let plot_id = ctx.request.body.plot_id
	let type = ctx.request.body.type
	let district = ctx.request.body.district
	let deploy = ctx.request.body.deploy
	let floor = ctx.request.body.floor
	let floor_sum = ctx.request.body.floor_sum
	let area = ctx.request.body.area
	let price = ctx.request.body.price
	let house_state = 3

	let sql = "insert into houses values(null," + state + ",null," + plot_id + "," + house_state + ",'" +
		type + "','" + district + "','" + deploy + "','" + floor + "','" + floor_sum + "','" + area +
		"','" + price + "','" + title + "','" + district + "','" + phone + "')"

	await sqlquery(sql);



	ctx.body = {
		code: '200',
		msg: '新增成功'
	}
})


//房源数据修改
router.post('/sethouses', async function(ctx, next) {
	let id = ctx.request.body.id
	let title = ctx.request.body.title
	let describes = ctx.request.body.describes
	let phone = ctx.request.body.phone
	let plot_id = ctx.request.body.plot_id
	let type = ctx.request.body.type
	let district = ctx.request.body.district
	let deploy = ctx.request.body.deploy
	let floor = ctx.request.body.floor
	let floor_sum = ctx.request.body.floor_sum
	let area = ctx.request.body.area
	let price = ctx.request.body.price


	let sql = "update houses set title='" + title + "',describes='" + describes + "',phone='" + phone +
		"',plot_id=" + plot_id + ",type='" + type + "',district='" + district + "',deploy='" + deploy +
		"',floor='" + floor + "',floor_sum='" + floor_sum + "',area='" + area + "',price='" + price +
		"' where id=" + id;

	await sqlquery(sql);


	ctx.body = {
		code: '200',
		msg: '修改成功'
	}
})

//新建房源图片
router.post('/uphousesimg', upload.single('file'), async (ctx, next) => {
	let file = ctx.req.file.filename
	file = '/uploads/' + file
	let imgtype = ctx.req.body.imgtype
	let openid = 999
	let sql = "insert into house_img values(null,'" + file + "',null," + imgtype + ",'" + openid + "')"
	await sqlquery(sql)
	ctx.body = {
		code: '200',
		msg: '新建图片成功',

	}
});


//确定房源图片
router.get('/enhousesimg', upload.single('file'), async (ctx, next) => {
	let sql = "select * from houses order by id desc limit 1";
	let res = await sqlquery(sql)
	let house_id = res[0].id
	console.log(555, house_id)
	let sql2 = "update house_img set house_id=" + house_id + " where openid='999'";
	console.log(sql2)
	await sqlquery(sql2)
	ctx.body = {
		code: '200',
		msg: '确定房源图片成功'
	}
});

//获取所有的经纪人
router.get('/getbroker', async function(ctx, next) {

	let sql = "select * from broker";

	let res = await sqlquery(sql);

	ctx.body = {
		code: '200',
		msg: '查询成功',
		res
	}
})

//分配房源给经纪人
router.post('/allotbroker', upload.single('file'), async (ctx, next) => {
	let broker_id = ctx.request.body.broker_id
	let id = ctx.request.body.id
	let sql = "update houses set broker_id=" + broker_id + " where id=" + id;
	await sqlquery(sql)
	ctx.body = {
		code: '200',
		msg: '分配房源成功'
	}
});



//团购数据查询
router.get('/getgroup_purchase', async function(ctx, next) {

	let title = ctx.query.title

	let sql = "select * from group_purchase";

	if (title) {
		sql += " and buy_title like '%" + title + "%'"
	}

	let res = await sqlquery(sql);


	ctx.body = {
		code: '200',
		msg: '查询成功',
		res
	}
})


//审核房源数据查询
router.get('/audithouses', async function(ctx, next) {

	let sql =
		"select houses.*,plot.plot_site from houses join plot on houses.plot_id = plot.id where houses.house_state=3";

	let res = await sqlquery(sql);


	ctx.body = {
		code: '200',
		msg: '查询成功',
		res
	}
})


//审核房源图片查询查询
router.get('/audithouses_img', async function(ctx, next) {
	let house_id = ctx.query.id

	let sql = "select * from house_img where house_id=" + house_id;

	let res = await sqlquery(sql);


	ctx.body = {
		code: '200',
		msg: '查询成功',
		res
	}
})


//审核房源
router.post('/audithouseslist', async function(ctx, next) {
	let id = ctx.request.body.id
	let house_state = ctx.request.body.state

	let sql = "update houses set house_state=" + house_state + " where id=" + id

	await sqlquery(sql);


	ctx.body = {
		code: '200',
		msg: '审核成功'
	}
})



//获取用户信息
router.get('/getuser', async function(ctx, next) {
	let name = ctx.query.name

	let sql = "select * from clientlogin"

	if (name) {
		sql += " and user_nickName like '%" + name + "%' "
	}

	let res = await sqlquery(sql);


	ctx.body = {
		code: '200',
		msg: '查询成功',
		res
	}
})


//获取订单信息
router.get('/getorder', async function(ctx, next) {
	let name = ctx.query.name
	let state = parseInt(ctx.query.state)

	let sql =
		"select payment.id,payment.mouth,payment.time,payment.price,payment.order,payment.house_state,clientlogin.user_nickName,clientlogin.user_phone from payment join clientlogin on payment.user_openid=clientlogin.openid"


	if (name) {
		sql += " and (clientlogin.user_nickName like '%" + name + "%' or payment.order like '%" + name +
			"%' or clientlogin.user_phone like '%" + name + "%')"
	}

	if (state) {
		sql += " and payment.house_state=" + state;
	}

	let res = await sqlquery(sql);


	ctx.body = {
		code: '200',
		msg: '查询成功',
		res
	}
})


//订单数据删除
router.get('/delorder', async function(ctx, next) {
	let id = ctx.query.id

	let sql = "delete from payment where id=" + id;

	await sqlquery(sql);


	ctx.body = {
		code: '200',
		msg: '删除成功'
	}
})



//反馈数据查询
router.get('/getfeedback', async function(ctx, next) {
	let phone = ctx.query.phone
	let reply = 0

	let sql = "select * from problem where problem_reply='" + reply + "'";

	if (phone) {
		sql += " and problem_phone=" + phone;
	}

	let res = await sqlquery(sql);


	ctx.body = {
		code: '200',
		msg: '查询成功',
		res
	}
})

//回复反馈
router.post('/replyfeedback', async function(ctx, next) {
	let value = ctx.request.body.value
	let id = ctx.request.body.id

	let sql = "update problem set problem_reply='" + value + "' where id=" + id;


	await sqlquery(sql);


	ctx.body = {
		code: '200',
		msg: '回复成功'
	}
})

module.exports = router
